<template>
	<view class="cart-container">
		<block v-if="cartList.length">
			<scroll-view scroll-y="true">
				<view class="cart-header">
					<view class="iconfont icondianpu"></view>
					<text>{{ shopName }}</text>
					<view class="cart-operation" @click="cartOperation">{{ operation == 'settlement' ? '编辑' : '完成' }}</view>
				</view>
				<view class="cart-wrapper">
					<block v-for="(item, index) in cartList" :key="index">
						<view class="cart-goods">
							<view class="iconfont" :class="item.checked ? 'iconyuan_checked' : 'iconyuan_checkbox'" @click="singleElection(index)"></view>
							<navigator class="goods-img" :url="'/pages/goods/detail/detail?goods_id=' + item.goods_id">
								<image :src="$util.img(item.picture_info.pic_cover_small)" mode="aspectFill"></image>
							</navigator>
							<view class="goods-info">
								<navigator :url="'/pages/goods/detail/detail?goods_id=' + item.goods_id" class="goods-name">{{ item.goods_name }}</navigator>
								<text class="sku" v-if="item.sku_name">{{ item.sku_name }}</text>
								<view class="goods-sub-section">
									<text class="goods-price ns-text-color">
										<text class="unit">￥</text>
										{{ item.show_price.toFixed(2) }}
									</text>
									<uni-number-box
										:min="item.min_buy > 0 ? item.min_buy : 1"
										:max="item.max_buy > 0 ? item.max_buy : item.stock"
										:value="item.num"
										:modifyFlag="modifyFlag"
										size="small"
										@change="cartNumChange($event, index)"
										:index="index"
									/>
								</view>
							</view>
						</view>
					</block>
				</view>
			</scroll-view>
		</block>
		<block v-else>
			<view class="cart-empty">
				<image
					src=""
					mode="aspectFill"
					class="empty-img"
				></image>
				<text class="ns-text-color-gray">购物车空空如也！</text>
				<block v-if="token != ''">
					<navigator open-type="switchTab" url="/pages/index/index/index" class="ns-text-color">去逛逛</navigator>
					<ns-goods-recommend ref="goodsRecommend"></ns-goods-recommend>
				</block>
				<block v-else><navigator url="/pages/member/index/index" open-type="switchTab" class="ns-text-color">去登录</navigator></block>
			</view>
		</block>

		<view class="cart-bottom" v-if="cartList.length">
			<view class="all-election" @click="allElection">
				<view class="iconfont" :class="checkAll ? 'iconyuan_checked' : 'iconyuan_checkbox'"></view>
				<text>全选</text>
			</view>
			<view class="settlement-info">
				<text v-show="operation == 'settlement'">
					合计：
					<text class="ns-text-color">
						￥
						<text>{{ totalPrice }}</text>
					</text>
				</text>
			</view>
			
			<button type="primary" class="operation-btn" style="background-color: #ee331b !important" v-if="operation == 'settlement' " :class="totalCount == 0 ? 'disabled' : ''" @click="submit(99)">
				包月({{ totalCount }})
			</button>
			<button type="primary" class="operation-btn" :class="totalCount == 0 ? 'disabled' : ''" @click="submit">
				{{ operation == 'settlement' ? '结算' : '删除' }}({{ totalCount }})
			</button>
			
		
		</view>
		<loading-cover ref="loadingCover"></loading-cover>
	</view>
</template>

<script>
import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue';
import http from 'common/js/http.js';
import loadingCover from '@/components/loading/loading.vue';
import nsGoodsRecommend from '@/components/ns-goods-recommend/ns-goods-recommend.vue';
export default {
	components: {
		uniNumberBox,
		loadingCover,
		nsGoodsRecommend
	},
	data() {
		return {
			operation: 'settlement', // 操作 settlement:结算  delete:删除
			token: '',
			cartList: [],
			totalPrice: '0.00',
			totalCount: 0,
			checkAll: true,
			goodsLadderPreferential: [], // 商品阶梯优惠
			shopName: '',
			flag: false, //防重复标识
			modifyFlag: false ,//修改数量防重复
			uid:''
		};
	},
	methods: {
		/**
		 * 上拉加载
		 */
		onReachBottom() {
			this.$refs.goodsRecommend.getGoodsList();
		},
		/**
		 * 获取购物车数据
		 */
		getCartData() {
			this.sendRequest({
				url: 'System.Goods.cartList',
				success: res => {
					console.log('获取购物车数据==',res)
					if (res.code == 0) {
						// buyer_id
						// this.uid=res.data.cart_list[0].buyer_id
						console.log('uid====',this.uid)
						
						console.log('res.data.cart_list====',res.data.cart_list)
						if (res.data.cart_list.length ) {
							
							this.cartList = res.data.cart_list;
							if (this.cartList != null && this.cartList.length > 0) {
								this.shopName = this.cartList[0]['shop_name'];
								this.goodsLadderPreferential = JSON.parse(res.data.goods_ladder_preferential);

								this.cartList.forEach((item, index) => {
									item.checked = true;
									item.show_price = item.promotion_price;
									this.calculationGoodsPrice(item, index);
								});
								this.calculationTotalPrice();
							}
						} else {
							this.cartList = [];
						}
						this.$refs.loadingCover.hide();
					}
				},
				fail: res => {
					this.$refs.loadingCover.hide();
				}
			});
		},
		async cartNumChange(value, index) {
			let item = this.cartList[index];
			if (isNaN(parseInt(value))) return;
			if (item.num != value) {
				this.modifyFlag = true;
				uni.showLoading({
					title: '加载中'
				});
				await this.modifyCartNum(value, item, index);
			}
		},
		/**
		 * 修改购物车商品数量
		 * @param {Object} num
		 * @param {Object} item
		 * @param {Object} index
		 */
		async modifyCartNum(num, item, index) {
			num = parseInt(num) > parseInt(item.stock) ? item.stock : parseInt(num);
			if (num <= 0) {
				num = item.min_buy > 0 ? item.min_buy : 1;
			}
			let res = await this.sendRequest({
				url: 'System.Goods.modifyCartNum',
				data: { cart_id: item.cart_id, num: num },
				async: false,
				success: res => {}
			});
			if (res.code == 0) {
				this.cartList[index].num = num;
				this.cartList[index].show_price = this.cartList[index].promotion_price;
				this.calculationGoodsPrice(item, index);
				this.calculationTotalPrice();
			} else {
				this.$util.showToast({ title: res.message });
			}
		},
		/**
		 * 计算购物车总价
		 */
		calculationTotalPrice() {
			if (this.cartList.length) {
				let totalPrice = 0;
				let totalCount = 0;
				let siteAllElectionCount = 0;
				
				this.cartList.forEach(function(item) {
					if (item.checked) {
						totalPrice += item.show_price * item.num;
						totalCount += Number(item.num);
						siteAllElectionCount += 1;
					}
				});
				
				this.totalPrice = totalPrice.toFixed(2);
				this.totalCount = totalCount;
				this.modifyFlag = false;
				
				this.checkAll = this.cartList.length == siteAllElectionCount;
				uni.hideLoading();
			} else {
				this.totalPrice = '0.00';
				this.totalCount = 0;
			}
		},
		/**
		 * 单选
		 * @param {Object} index
		 */
		singleElection(index) {
			this.cartList[index].checked = !this.cartList[index].checked;
			this.cartList.push({});
			this.cartList.pop();
			let checkedNUm = 0;
			this.cartList.forEach(item => {
				if (item.checked) checkedNUm += 1;
			});
			this.checkAll = checkedNUm == this.cartList.length;
			this.calculationTotalPrice();
		},
		/**
		 * 全选
		 */
		allElection(checked) {
			if (typeof checked == 'boolean') {
				this.checkAll = checked;
			} else {
				this.checkAll = !this.checkAll;
			}
			if (this.cartList.length) {
				this.cartList.forEach(item => {
					item.checked = this.checkAll;
				});
				this.calculationTotalPrice();
			}
		},
		/**
		 * 购物车操作
		 */
		cartOperation() {
			if (this.operation == 'settlement') {
				this.operation = 'delete';
				this.allElection(false);
			} else {
				this.operation = 'settlement';
				this.allElection(true);
			}
		},
		/**
		 * 计算阶梯优惠之后的商品价格
		 */
		calculationGoodsPrice(cartItem, index) {
			var quantity = 0;
			if (this.goodsLadderPreferential.length) {
				this.goodsLadderPreferential.forEach(items => {
					if (items.length) {
						items.forEach(item => {
							if (item.quantity <= cartItem.num && item.quantity >= quantity && item.goods_id == cartItem.goods_id && item.cart_id == cartItem.cart_id) {
								quantity = item.quantity;
								this.cartList[index].show_price = this.cartList[index].promotion_price - item.price;
							}
						});
					}
				});
			}
		},
		submit(e) {
			if(e==99){
				console.log("eeeeeeeeeeeeeeeeeeeeeeee")
			}
			var cartIdArr = [],
				goodsSkuList = [];

			this.cartList.forEach(item => {
				if (item.checked) {
					cartIdArr.push(item.cart_id);
					goodsSkuList.push(item.sku_id + ':' + item.num);
				}
			});
			if (this.operation == 'settlement') {
				if (!goodsSkuList.length) {
					this.$util.showToast({ title: '请选择要结算的商品！' });
					return;
				}

				if (this.flag) return;
				this.flag = true;

				uni.setStorage({
					key: 'orderCreateData',
					data: JSON.stringify({
						order_type:e==99?99:1,
						goods_sku_list: goodsSkuList.toString(),
						order_tag: 2,
					}),
					success: res => {
						console.log("555555555555555555",res)
					
							this.$util.redirectTo('/pages/order/payment/payment');
						
					}
				});
			} else {
				if (!cartIdArr.length) {
					this.$util.showToast({ title: '请选择要删除的商品！' });
					return;
				}

				if (this.flag) return;
				this.flag = true;
				this.sendRequest({
					url: 'System.Goods.deleteCart',
					data: { 
						cart_id_array: cartIdArr.toString(),
						uid:this.uid
					 },
					success: res => {
						console.log('cart_id_array=',cartIdArr.toString())
						if (res.code == 0) {
							console.log('删除成功')
							for (var i = 0; i < this.cartList.length; ) {
								if (this.$util.inArray(this.cartList[i].cart_id, cartIdArr) != -1) {
									this.cartList.splice(i, 1);
									i = 0;
									continue;
								}
								i++;
							}
							this.calculationTotalPrice();
						} else {
							this.$util.showToast({ title: res.message });
						}
						this.flag = false;
					}
				});
			}
		}
	},
	onShow() {
		this.token = uni.getStorageSync('token');
		
		if (this.token) this.getCartData();
		else this.cartList = [];
	},
	onReady() {
		this.$refs.loadingCover.hide();
	},
	onHide() {
		this.flag = false;
	},
	mixins: [http]
};
</script>

<style lang="scss">
scroll-view {
	/*  #ifdef H5 */
	height: calc(100vh - 94px);
	/*  #endif  */
	/*  #ifdef MP */
	height: calc(100vh - 0px);
	/*  #endif  */
}
.cart-container {
	box-sizing: border-box;
	position: relative;
	width: 100vw;
	overflow: scroll;
}
.cart-container .cart-header {
	padding: 20rpx;
	overflow: hidden;
	line-height: 1;

	.icondianpu {
		float: left;
		display: inline-block;
		margin-right: 20rpx;
	}

	.cart-operation {
		float: right;
	}
	view,
	text {
		line-height: 37rpx;
	}
}
.cart-container .cart-wrapper {
	padding-bottom: 100rpx;

	.cart-goods {
		margin: 0 24rpx 24rpx 24rpx;
		border-radius: 4px;
		background: #fff;
		box-sizing: border-box;
		position: relative;
		padding-left: 76rpx;
		display: flex;

		& > .iconfont {
			font-size: 36rpx;
			position: absolute;
			top: 50%;
			left: 24rpx;
			transform: translateY(-50%);
		}
		& > .iconyuan_checked {
			color: $base-color;
		}
		& > .iconyuan_checkbox {
			color: $ns-text-color-gray;
		}
		.goods-img {
			width: 180rpx;
			height: 180rpx;
			padding: 24rpx 0;
			margin-right: 24rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.goods-info {
			flex: 1;
			padding: 24rpx 0;
			position: relative;

			.goods-name {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				line-height: 1.5;
				font-size: 28rpx;
				padding-right: 20rpx;
			}

			.sku {
				font-size: 24rpx;
				color: #999;
				display: block;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				padding-right: 20rpx;
			}

			.goods-sub-section {
				position: absolute;
				left: 0;
				bottom: 24rpx;
				width: calc(100% - 24rpx);

				.unit {
					font-size: 24rpx;
				}

				.uni-numbox {
					float: right;
				}
			}
		}
	}
}
.cart-container .cart-bottom {
	position: absolute;
	z-index: 5;
	width: 100vw;
	height: 100rpx;
	background: #fff;
	bottom: 0;
	overflow: hidden;
	display: flex;

	.all-election {
		height: 100rpx;
		position: relative;
		padding-left: 20rpx;
		display: inline-block;

		& > .iconfont {
			font-size: 36rpx;
			position: absolute;
			top: 50%;
			left: 24rpx;
			transform: translateY(-50%);
		}
		& > .iconyuan_checked {
			color: $base-color;
		}

		& > text {
			margin-left: 56rpx;
			line-height: 100rpx;
		}
	}

	.settlement-info {
		flex: 1;
		text-align: right;
		padding-right: 20rpx;
		line-height: 100rpx;
	}

	.operation-btn {
		width: 180rpx;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: 0;
		margin: 0;
	}
	.operation-btn.disabled {
		background: $btn-disabled-color !important;
		border: none !important;
	}
}
.cart-empty {
	text-align: center;
	font-size: 24rpx;
	padding: 0 $ns-padding;
	.empty-img {
		margin: 200rpx auto 20rpx auto;
		width: 220rpx;
		height: 120rpx;
		display: block;
	}
	navigator {
		display: inline;
	}
}
</style>
